from fastapi import FastAPI, Response, Request
from fastapi.responses import PlainTextResponse, HTMLResponse
from cryptography.fernet import Fernet

app = FastAPI()

COOKIE_ENCRYPTION_KEY = Fernet.generate_key()  # 随机生成密钥
# COOKIE_ENCRYPTION_KEY = b'wabvJHHrgFsBPQMEpsV-eJdW0NjcG3NgRBWepnu8VnM='
print(f"COOKIE_ENCRYPTION_KEY={COOKIE_ENCRYPTION_KEY}")

fernet = Fernet(COOKIE_ENCRYPTION_KEY)


@app.get("/")
async def main(request: Request):
    secure_count = request.cookies.get("page_count")
    if secure_count is None:
        page_count = 0
    else:
        page_count = int(fernet.decrypt(secure_count.encode("utf-8")))

    page_count += 1
    secure_count = fernet.encrypt(str(page_count).encode("utf-8"))

    resp = PlainTextResponse(content=f"Count={page_count}")
    resp.set_cookie(
        key="page_count",
        value=secure_count.decode(),
        secure=True,
        httponly=True,
        samesite="strict",
    )
    return resp


@app.get("/del")
async def del_cookie():
    resp = HTMLResponse(
        content="""
    <html><body>
    <h4><a href="/">返回根页面</a></h4>
    删除 page_count Cookie.
    </body></html>
    """,
        status_code=200,
    )
    resp.delete_cookie("page_count")
    return resp
